#!/usr/bin/python
#encoding=utf-8

import os,time
import multiprocessing
from wm.lib import util
from wm.lib import websitelib,monitorlib
from wm.lib import tcpcheck,udpcheck
from wm.lib import senword
from wm.lib import downloadspeed
from wm.lib import htmlloadtime
from wm.lib import responsetime
from wm.lib import websitealive
from wm.lib import vulscaning
from wm.lib import pagetamper
from wm.lib.loglib import log_error
from wm.etc.config import MONITOR,CLUSTER 
from apscheduler.scheduler import Scheduler

def debug_process(mname):
    print mname 
    print 'pid',os.getpid()
    
def monitor_website_port(cluster):
    '''
          网站首页端口扫描监控:TCP和、UDP
    '''
    sched = Scheduler(daemonic=False)
    sitelist = monitorlib.get_website_list(cluster)

    if sitelist:
        for row in sitelist:
            url = websitelib.website_get_newUrl(row[1])
            spix = url.find(':')  
                      
            ports = util.tsplit(str(row[3]), ';')
            for tcpport in ports:
                if tcpport:
                    if spix != -1:
                        tcpport = url[spix+1:]
                        url = url[0:spix]
                    sched.add_interval_job(tcpcheck.tcp_check_alarm, seconds=int(row[11]), args=[url,tcpport, row]) 
                    
            ports = util.tsplit(str(row[4]), ';')
            for udpport in ports:
                if udpport:
                    if spix != -1:
                        udpport = url[spix+1:]
                        url = url[0:spix]
                    sched.add_interval_job(udpcheck.udp_check_alarm, seconds=int(row[11]), args=[url,udpport, row])  
    
    sched.start()
    
    while True:pass
    
    
def monitor_download_speed_index(cluster):
    '''
         首页下载速度
    '''
    #sched = Scheduler(daemonic=False)
    while True:
        sitelist = monitorlib.get_website_list(cluster)
        debug_process("speed") 
            
        if sitelist:
            for row in sitelist:
                downloadspeed.download_speed_alarm(row)  
                #sched.add_interval_job(downloadspeed.download_speed_alarm, minutes=int(row[5]), args=[row]) 
        
        #sched.start()
        #while True:pass
        time.sleep(2103)
        
def monitor_website_index(cluster):
    '''
    网页首页存活入口函数
    '''
    #sched = Scheduler(daemonic=False)
    while True:
        sitelist = monitorlib.get_website_list(cluster)
        
        debug_process("alive")
            
        if sitelist:
            for row in sitelist:
                websitealive.website_status_alarm(row)
                #sched.add_interval_job(websitealive.website_status_alarm, minutes=int(row[11]), args=[row]) 
                
        #sched.start()    
        #while True:pass
        time.sleep(600)    
        
def monitor_htmlload_time_index(cluster):
    ''' 
	计算网站首页html加载时间
	'''
    #sched = Scheduler(daemonic=False)
    while True:
        sitelist = monitorlib.get_website_list(cluster)        
        debug_process("loadtime")
            
        if sitelist:
            for row in sitelist:
                htmlloadtime.html_load_time_alarm(row)
                #sched.add_interval_job(htmlloadtime.html_load_time_alarm, minutes=int(row[9]), args=[row]) 
        
        #sched.start()
        #while True:pass
        time.sleep(1800)
    
def monitor_response_time_index(cluster):
    ''' 
	计算网站首页响应时间
	'''
    while True:
        #sched = Scheduler(daemonic=False)
        sitelist = monitorlib.get_website_list(cluster)
        debug_process("restime")
            
        if sitelist:
            for row in sitelist:
                responsetime.response_time_alarm(row)
                #sched.add_interval_job(responsetime.response_time_alarm, minutes=int(row[10]), args=[row]) 
            
        time.sleep(1900)
        #sched.start()
        #while True:pass
 
def monitor_words_index(cluster):
    ''' 
            监测网站首页的敏感字
    '''
    sched = Scheduler(daemonic=False)
    sitelist = monitorlib.get_website_list(cluster)
    fkw_dic = senword.get_fkw_dic()
    debug_process("senwords")
        
    if sitelist:
        for row in sitelist:
            sched.add_interval_job(senword.sensitive_words_check, minutes=int(row[12]), args=[row,fkw_dic]) 
    
    sched.start()
    while True:pass
        
def monitor_vulscaning_website(cluster):
    '''
	启动漏洞扫描任务
    '''
    sched = Scheduler(daemonic=False)
    sitelist = monitorlib.get_website_list(cluster)    
    debug_process("vulscanning")
                
    if sitelist:
        for row in sitelist:
            sched.add_cron_job(vulscaning.vulscaning, month='*', day='?', week='sun', hour='1', minute='10', second='0', args=[row[0],row[1]])
    sched.start()
    
    while True:pass 
     
def monitor_pagetamper_index(cluster):
    '''
          网站首页篡改检测
    '''
    sched = Scheduler(daemonic=False)
    palist = monitorlib.get_pageanalyzes()   
    debug_process("pagetamer")

    if palist:
        for pa in palist:
            sched.add_interval_job(pagetamper.page_tamper_monitor, minutes=pa[6], args=[pa])
            
    sched.start()
    
    while True:pass 
    
  
monitor_function = {
                    "vulscaning":monitor_vulscaning_website, 
                    "senwords":monitor_words_index,
                    "restime":monitor_response_time_index,
                    "htmlloadtime":monitor_htmlload_time_index,
                    "webalive":monitor_website_index,
                    "downloadspeed":monitor_download_speed_index,
                    "websiteport":monitor_website_port
                    #"pagetamper":monitor_pagetamper_index
                    } 


   
def main(cluster):
    '''
	主函数，为每个功能模块启动一个进程执行任务，每个任务由一个线程来完成响应的任务
	'''
    while True:
        pool = multiprocessing.Pool(processes = MONITOR['maxprocessing'])  
        try:
            for key in monitor_function:
                pool.apply_async(monitor_function[key],(cluster,))
                print 'start module:',key
        except Exception as e:
            log_error("core_monitor:"+str(e))   
        time.sleep(0.3)
        pool.close()
        pool.join() 

 
if __name__ == '__main__':
    #should be first line for py2exe
    multiprocessing.freeze_support()
    #taskkill /F /IM python.exe
    main(CLUSTER['cluster'])
    
    